package com.demo.generator;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * todo 分页查询接口需要通过 fm 重写；dto需要重写
 */
public class CodeGeneratorTalSpier {

    /**
     * 数据库连接驱动 不用修改
     */
    private static final String driverName = "com.mysql.cj.jdbc.Driver";

    /**
     * todo 1、修改数据库信息  连接名、账号、密码
     * 数据库地址链接
     */
    private static final String datasource =
              "jdbc:mysql://10.202.5.130:3306/spier_data?charset=utf8mb4&autoReconnect=true&zeroDateTimeBehavior=" +
                      "CONVERT_TO_NULL&serverTimezone=Asia/Shanghai&characterEncoding=UTF-8&useUnicode=yes";

//    private static final String datasource =
//            "jdbc:mysql://10.202.5.130:3306/at_open?charset=utf8mb4&autoReconnect=true&zeroDateTimeBehavior=" +
//                    "CONVERT_TO_NULL&serverTimezone=Asia/Shanghai&characterEncoding=UTF-8&useUnicode=yes";



    /**
     * 数据库登录名
     */
    private static final String login = "rdsroot";

    /**
     * 数据库登录密码
     */
    private static final String password = "xxx";

    /**
     * todo 2、修改要生成的表名
     * 要创建代码的数据库表明，多个表用,分割
     */
//    private static final String tableNames = "user_activity_info";
//    private static final String tableNames = "reward_record";
//    private static final String tableNames = "invitation_relation";
//    private static final String tableNames = "activity_resource";
//    private static final String tableNames = "activity_config";
//    private static final String tableNames = "advertisement";
//    private static final String tableNames = "multimodal_intent_record";

//    private static final String tableNames = "user";
//    private static final String tableNames = "param_test";



//    private static final String tableNames = "mathat_config_open";
//    private static final String tableNames = "open_api_log";


//    private static final String tableNames = "open_server_app";


    private static final String tableNames = "area_info";
//    private static final String tableNames = "area";
//    private static final String tableNames = "teacher_class";
//    private static final String tableNames = "teacher_subject";
//    private static final String tableNames = "subject";
//    private static final String tableNames = "student";
//    private static final String tableNames = "teacher";
//    private static final String tableNames = "class_info";
//    private static final String tableNames = "grade";
//    private static final String tableNames = "invite_code";
//    private static final String tableNames = "school";
//    private static final String tableNames = "user";

    /**
     * todo 3、设定要输出的文件目录
     * 输出文件夹
     */
//    private static final String outputPath = "D://generator/java/"+System.currentTimeMillis();
    private static final String outputPath = "/Users/tal/Develop/generator";
//    private static final String outputPath = "/Users/tal/Develop/mathgpt_project/mathgpt-at-server";

    /**
     * todo 4、设定包名
     * 输出包名
     */
    private static final String packageInfo = "com.tal.mathgpt";

    /**
     * 输出模块名
     */
    private static final String moduleName = "test";

    /**
     * 如果模板引擎是 freemarker
     * 如果模板引擎是 velocity
     * String templatePath = "/templates/mapper.xml.vm";
     */
    private static final String mapperXmlTemplatePath = "/templates/mapper.xml.ftl";;

    /**
     * mapper模版引擎
     */
    private static final String mapperTemplatePath = "/templates/mapper.java.ftl";;

    /**
     * 是否开启swagger2
     */
    private static final boolean swaggerFlag = false;

    /**
     * 代码模块 路径
     */
    private static final String modulePath = "mathat";



    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // java代码输出位置配置,和全局配置
        GlobalConfig gc = initOutput();
        // 实体属性 Swagger2 注解 禁用
        gc.setSwagger2(swaggerFlag);
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = initDatasourceConfig();
        mpg.setDataSource(dsc);

        // 代码包名配置
        PackageConfig pc = initPackageConfig();
        mpg.setPackageInfo(pc);

        // mapper.xml自定义配置
        InjectionConfig cfg = initConfig(pc);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = initTemplateConfig();
        mpg.setTemplate(templateConfig);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());

        // 类相关策略配置
        StrategyConfig strategy = initClassConfig();
        mpg.setStrategy(strategy);

        //执行创建模板
        mpg.execute();
    }

    private static StrategyConfig initClassConfig() {
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
//        strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
//        strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
        // todo 暂时取消自定义父类设置，使用 MP 现有的基类接口
//        strategy.setSuperServiceClass("com.group.parent.database.base.BaseService");
//        strategy.setSuperServiceImplClass("com.group.parent.database.base.BaseServiceImpl");
//        strategy.setSuperMapperClass("com.baomidou.mybatisplus.core.mapper.BaseMapper");
        // 写于父类中的公共字段
//        strategy.setSuperEntityColumns("id");
        strategy.setInclude(tableNames.split(","));
//        strategy.setControllerMappingHyphenStyle(true);
//        strategy.setTablePrefix("t_");

        return strategy;
    }

    private static TemplateConfig initTemplateConfig() {
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定义输出模板
        //指定自定义模板路径，注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别  采用 freemarker模板引擎
        templateConfig.setController("templates/controller.java");
        templateConfig.setService("templates/service.java");
        templateConfig.setServiceImpl("templates/serviceImpl.java");
//         templateConfig.setEntity("templates/entity2.java");
        templateConfig.setMapper("templates/mapper.java");

        templateConfig.setXml(null); // mapper.xml 采用了自定义配置

        return templateConfig;
    }


    private static InjectionConfig initConfig(PackageConfig pc) {

        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                /**
                 * import com.tal.mathat.common.HttpResult;
                 * import com.tal.mathat.dto.input.OpenServerAppInputDTO;
                 * import com.tal.mathat.dto.input.SelectOpenServerAppInputDTO;
                 * import com.tal.mathat.dto.output.OpenServerAppOutputDTO;
                 */

                // to do nothing
                Map<String, Object> map = new HashMap<>();
                map.put("swaggerFlag", swaggerFlag);
                map.put("packageInfo", packageInfo);
                map.put("modulePath", modulePath);

                setMap(map);
            }

            /**
             * 依据表相关信息，从三方获取到需要元数据，处理方法环境里面
             *
             * @param tableInfo
             */
            @Override
            public void initTableMap(TableInfo tableInfo) {
                // 子类重写注入表对应补充信息
                String serviceName = tableInfo.getServiceName();
                // 修改Service接口名称 去除I前缀 为了适配框架代码
                tableInfo.setServiceName(serviceName.substring(1));
            }
        };

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(mapperXmlTemplatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return outputPath + "/src/main/resources/mapper/"
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(focList);
        return cfg;
    }

    private static PackageConfig initPackageConfig() {
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(null);
        pc.setParent(packageInfo);
        pc.setMapper("dao");
        return pc;
    }

    private static DataSourceConfig initDatasourceConfig() {
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(datasource);
        dsc.setDriverName(driverName);
        dsc.setUsername(login);
        dsc.setPassword(password);
        return dsc;
    }

    private static GlobalConfig initOutput() {
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(outputPath + "/src/main/java");
        // todo 修改author
        gc.setAuthor("gy");
        gc.setOpen(false);
        gc.setFileOverride(true);//是否覆盖已经生成的
        gc.setBaseResultMap(true);
        gc.setBaseColumnList(true);
        return gc;
    }

}
